<template>
  <div class="publish">
    <video ref="video"></video>
    <canvas style="display: none" id="canvasCamera"></canvas>
    <div v-if="imgSrc" class="img_bg_camera">
      <h2>验证图片</h2>
      <img :src="imgSrc" class="tx_img" />
    </div>
    <div class="button-group">
      <button @click="OpenCamera">打开摄像头</button>
    <button @click="CloseCamera">关闭摄像头</button>
    </div>
    
    <!-- <button @click="setImage">拍照</button> -->

  <!-- 单选按钮组 -->
  <div class="radio-group">
    <label>
      <input type="radio" value="揽收" v-model="selectedMethod" /> 揽收
    </label>
    <label>
      <input type="radio" value="发货" v-model="selectedMethod" /> 发货
    </label>
    <label>
      <input type="radio" value="收货" v-model="selectedMethod" /> 收货
    </label>
  </div>

  <!-- 显示当前选择 -->
  <div class="current-selection">
    <h2>当前选择: {{ selectedMethod }}   验收模式</h2>
  </div>

  <!-- 根据选择的值执行不同的操作 -->
  <div class="execute-button">
    <button @click="executeMethod">扫码验证</button>
  </div>
</div>



</template>

  
  <script>
  export default {
    data() {
      return {
        mediaStreamTrack: {},
        video_stream: '', // 视频stream
        imgSrc: '', // 拍照图片
        canvas: null,
        context: null,
        selectedMethod: '',
        formData: new FormData(),
      };
    },
    mounted() {
      // 进入页面 自动调用摄像头
      this.getCamera();
    },
    methods: {
// 执行不同的方法，根据选中的值来调用不同的处理函数
executeMethod() {
      switch (this.selectedMethod) {
        case "揽收":
          this.method1();
          break;
        case "发货":
          this.method2();
          break;
        case "收货":
          this.method3();
          break;
        default:
          alert("请先选择一个方法");
      }
    },
    async method1(){
      console.log('揽收');
      this.formData = new FormData();
      this.setImage();
    try {
      // 发送图片到后端
      this.$axios.post('apil/logis/CollectingInfo', this.formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
    } catch (error) {
      console.error('图片上传失败', error);
    }
    },
    method2(){
      console.log('发货');
      this.formData = new FormData();
      this.setImage();
    try {
      // 发送图片到后端
      this.$axios.post('apil/logis/SendingInfo', this.formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
    } catch (error) {
      console.error('图片上传失败', error);
    }
    },
    method3(){
      console.log('收货');
      this.formData = new FormData();
      this.setImage();
    try {
      // 发送图片到后端
      this.$axios.post('apil/logis/SignForInfo', this.formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
    } catch (error) {
      console.error('图片上传失败', error);
    }
    },



      // 调用打开摄像头功能
      getCamera() {
        // 获取 canvas 画布
        this.canvas = document.getElementById('canvasCamera');
        this.context = this.canvas.getContext('2d');
        // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
        if (navigator.mediaDevices === undefined) {
          navigator.mediaDevices = {};
        }
        // 正常支持版本
        navigator.mediaDevices
          .getUserMedia({
            video: true,
          })
            .then((stream) => {
            // 摄像头开启成功
            this.mediaStreamTrack = typeof stream.stop === 'function' ? stream : stream.getTracks()[0];
            this.video_stream = stream;
            this.$refs.video.srcObject = stream;
            this.$refs.video.play();
          })
          .catch(err => {
            console.log(err);
          });
      },
      // // 拍照 绘制图片
//       setImage() {
//         console.log('拍照');
//         // 点击canvas画图
//         this.context.drawImage(
//           this.$refs.video,
//           0,
//           0,
//           200,
//           100,
//         );

// // 假设 this.canvas 是你的 HTMLCanvasElement
// const image = this.canvas.toDataURL('image/png');

// // 创建 URLSearchParams 对象
// const params = new URLSearchParams();
// params.append('image', image);

// // 发送 POST 请求
// this.$axios.post('api/logis/uploadImage', params, {
//   headers: {
//     'Content-Type': 'application/x-www-form-urlencoded'
//   },
// })
// .then(response => {
//   console.log('Image uploaded successfully:', response.data);
// })
// .catch(error => {
//   console.error('There was an error uploading the image!', error);
// });
//   },
    async setImage() {
    console.log('拍照');
  
    // 检查 video 和 canvas 是否存在
    if (!this.$refs.video || !this.canvas) {
      console.error('Video or canvas element not found');
      return;
    }
  
    // 绘制视频帧到 canvas
    this.context.drawImage(this.$refs.video, 0, 0, 200, 100);
  
    // 获取图片的 Base64 链接
    const imageBase64 = this.canvas.toDataURL('image/png');
    this.imgSrc = imageBase64;
    this.$emit('refreshDataList', this.imgSrc);
  


    //   // 将 Base64 转换为 Blob
      const blob = await this.dataURLToBlob(imageBase64);
    //   // 创建 FormData 对象
      
      this.formData.append('image', blob, 'captured-image.png');




  },
  
  // 辅助函数：将 Base64 转换为 Blob
  dataURLToBlob(dataURL) {
    return new Promise((resolve, reject) => {
      try {
        const arr = dataURL.split(',');
        const mime = arr[0].match(/:(.*?);/)[1];
        const bstr = atob(arr[1]);
        let n = bstr.length;
        const u8arr = new Uint8Array(n);
  
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
  
        resolve(new Blob([u8arr], { type: mime }));
      } catch (err) {
        reject(err);
      }
    });
  },
  
      // 打开摄像头
      OpenCamera() {
        console.log('打开摄像头');
        this.getCamera();
      },
      // 关闭摄像头
      CloseCamera() {
        console.log('关闭摄像头');
        this.$refs.video.srcObject.getTracks()[0].stop();
      },
    },
  };
  </script>
  
  <style lang="less" scoped>
  .publish {
  display: flex;
  flex-direction: column;
  align-items: center;

  video {
    width: 100%;
    height: 300px;
  }
  canvas {
    width: 100%;
    height: 300px;
  }
  button {
    width: 100px;
    height: 40px;
    position: relative;
    bottom: 0;
    left: 0;
    background-color: rgb(22, 204, 195);
  }
  .img_bg_camera {
    img {
      width: 300px;
      height: 200px;
    }
  }



  .button-group {
      display: flex;
      justify-content: space-around;
      margin-top: 10px;

      button {
        width: 100px;
        height: 40px;
        background-color: rgb(22, 204, 195);
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        transition: background-color 0.3s ease;

        &:hover {
          background-color: darken(rgb(22, 204, 195), 10%);
        }
      }
    }

    .radio-group {
    display: flex;
    justify-content: space-around;
    width: 100%;
    max-width: 600px;
    margin-bottom: 20px;

    label {
      display: flex;
      align-items: center;

      input {
        margin-right: 5px;
      }
    }
  }

  .current-selection {
    width: 100%;
    max-width: 600px;
    margin-bottom: 20px;
    text-align: center;

    h2 {
      font-size: 18px;
      color: #333;
    }
  }

  .execute-button {
    width: 100%;
    max-width: 600px;
    text-align: center;

    button {
      width: 150px;
      height: 40px;
      background-color: rgb(22, 204, 195);
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      transition: background-color 0.3s ease;

      &:hover {
        background-color: darken(rgb(22, 204, 195), 10%);
      }
    }
  }
}

  </style>